package com.example.demo.service.impl;

        import com.alibaba.fastjson.JSON;
        import com.alibaba.fastjson.JSONObject;
        import com.alibaba.fastjson.JSONPObject;
        import com.example.demo.po.GeneticTestingPackage;
        import com.example.demo.service.EsService;
        import org.elasticsearch.action.index.IndexResponse;
        import org.elasticsearch.client.transport.TransportClient;
        import org.elasticsearch.common.settings.Settings;
        import org.elasticsearch.common.transport.TransportAddress;
        import org.elasticsearch.common.xcontent.XContentType;
        import org.elasticsearch.transport.client.PreBuiltTransportClient;
        import org.slf4j.Logger;
        import org.slf4j.LoggerFactory;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.stereotype.Service;

        import java.net.InetAddress;
        import java.net.UnknownHostException;

/**
 * @Description: //TODO
 * @ProjectName: demo6
 * @Package: com.example.demo.service.impl
 * @Author: FX
 * @CreateDate: 2018/10/27 10:18
 * @Version: 1.0
 * Copyright: Copyright (c) 2018
 */
@Service
public class EsServiceImpl implements EsService {

    private static Logger logger = LoggerFactory.getLogger(EsServiceImpl.class);
    public final static String HOST = "127.0.0.1";
    // http请求的端口是9200，客户端是9300
    public final static int PORT = 9300;
    //客户端
    private static TransportClient client;

    /**
     * getConnection:(获取es连接).
     *
     * @return
     * @throws Exception
     * @author xbq Date:2018年3月21日上午11:52:02
     */
    @SuppressWarnings({"resource", "unchecked"})
    public static TransportClient getConnection()  {
        try {
            // 设置集群名称
            Settings settings = Settings.builder()/*.put("cluster.name", "nmtx-cluster")*/.build();
            // 创建client
            client = new PreBuiltTransportClient(settings)
                    .addTransportAddresses(new TransportAddress(InetAddress.getByName(HOST), PORT));

            return client;
        } catch (UnknownHostException e) {
            e.printStackTrace();
            System.out.println("链接失败");
            return null;
        }
    }

    /**
     * 添加es
     * @param geneticTestingPackage
     * @return
     */
    @Override
    public boolean addes(GeneticTestingPackage geneticTestingPackage){
        TransportClient client = getConnection();
        JSONObject jsonObject= (JSONObject) JSON.toJSON(geneticTestingPackage);
        IndexResponse response =client.prepareIndex("testes", "package",geneticTestingPackage.getId()).setSource(jsonObject.toString(), XContentType.JSON).get();
        System.out.println(jsonObject);
        System.out.println(response.getResult());
        System.out.println(response.status());
        logger.debug("索引为"+response.getIndex()+"--类型为"+response.getIndex()+"--id为"+response.getId());
        return true;
    }
}
